//
// Created by Administrator on 2020/10/14.
//

#include <getopt.h>
#include "../include/cnApi.h"
#include "../amf/include/amfApi.h"
#include "../smf/include/smfApi.h"
#include "../upf/include/upfApi.h"

S_CnContext* gpCnContext = NULL;

int32_t CN_Init(int argc, char* argv[])
{
    int32_t rc;

    rc = LOG_Init();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Init() LOG_Init() error!\n");

    LOG_SetAppType("CN");
    LOG_SetModuleNameTable(gCnModuleNameTable, CN_MD_BUTT, CN_MODULE_NAME_PREFIX_LEN);

    rc = CN_MP_Init();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Init() CN_MP_Init() error!\n");

    gpCnContext = OS_MemCalloc(1, sizeof(S_CnContext));
    IF_RETURN(==, NULL, gpCnContext, O5G_RC_ER, "CN_Init() OS_MemCalloc() error!\n");

    rc = AMF_Init();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Init() AMF_Init() error!\n");

    rc = SMF_Init();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Init() SMF_Init() error!\n");

    rc = UPF_Init();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Init() UPF_Init() error!\n");

    CSP_LOG_INF(CN_MD_COMM, "CN_Init() success.\n");

    return O5G_RC_OK;
}

int32_t CN_Final(void)
{
    int32_t rc;

    rc = AMF_Final();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Final() AMF_Final() error!\n");

    rc = SMF_Final();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Final() SMF_Final() error!\n");

    rc = UPF_Final();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Final() UPF_Final() error!\n");

    OS_MemFree(gpCnContext);

    rc = CN_MP_Final();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Final() CN_MP_Final() error!\n");

    CSP_LOG_INF(CN_MD_COMM, "CN_Final() success.\n");

    rc = LOG_Final();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Final() LOG_Final() error!\n");

    return O5G_RC_OK;
}

int32_t CN_Start(void)
{
    int32_t rc;

    rc = AMF_Start();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Start() AMF_Start() error!\n");

    rc = SMF_Start();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Start() SMF_Start() error!\n");

    rc = UPF_Start();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Start() UPF_Start() error!\n");

    CSP_LOG_INF(CN_MD_COMM, "CN_Start() success.\n");

    return O5G_RC_OK;
}

int32_t CN_Stop(void)
{
    int32_t rc;

    rc = AMF_Stop();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Stop() AMF_Stop() error!\n");

    rc = SMF_Stop();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Stop() SMF_Stop() error!\n");

    rc = UPF_Stop();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "CN_Stop() UPF_Stop() error!\n");

    CSP_LOG_INF(CN_MD_COMM, "CN_Stop() success.\n");

    return O5G_RC_OK;
}
